import { isNil } from 'lodash-es'

export const getSetter = (key) => (state, payload) => {
  if (isNil(payload)) return
  state[key] = payload
}

export const dateFormat = (date, format) => {
  format = format ? format : 'yyyy-MM-dd hh:mm:ss'
  if (date != 'Invalid Date') {
    var o = {
      'M+': date.getMonth() + 1, //month
      'd+': date.getDate(), //day
      'h+': date.getHours(), //hour
      'm+': date.getMinutes(), //minute
      's+': date.getSeconds(), //second
      'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
      S: date.getMilliseconds(), //millisecond
    }
    if (/(y+)/.test(format))
      format = format.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    for (var k in o)
      if (new RegExp('(' + k + ')').test(format))
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
    return format
  }
  return ''
}

export const convertToTimeFormat = (floatNumber) => {
  if (!floatNumber) return '00:00.000'
  if (floatNumber >= 86400) {
    return false
  }
  // 取整部分为总秒数
  const totalSeconds = Math.floor(floatNumber)
  // 取小数部分为毫秒数
  const milliseconds = (floatNumber - totalSeconds).toFixed(3).substring(2)

  // 计算小时
  const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
  // 计算分钟
  const minutes = String(Math.floor((totalSeconds % 3600) / 60)).padStart(
    2,
    '0'
  )
  // 计算秒
  const seconds = String(totalSeconds % 60).padStart(2, '0')
  if (hours > 0) {
    return `${hours}:${minutes}:${seconds}.${milliseconds}`
  } else {
    return `${minutes}:${seconds}.${milliseconds}`
  }
}

// 根据屏幕宽度 设计分页展示的数量

export const getPageSize = (width) => {
  width = width || document.body.clientWidth
  if (width < 992) {
    return 12
  } else if (width < 1200) {
    return 16
  } else if (width < 1600) {
    return 24
  } else {
    return 40
  }
}
